package com.sicnu.cheer.leaugebar.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.sicnu.cheer.generalmodule.activity.BaseActivity;
import com.sicnu.cheer.generalmodule.config.AppManager;
import com.sicnu.cheer.generalmodule.util.HttpAccessUtils;
import com.sicnu.cheer.generalmodule.util.NetWorkUtil;
import com.sicnu.cheer.generalmodule.util.ScreenUtils;
import com.sicnu.cheer.generalmodule.util.SharedPreferencesUtil;
import com.sicnu.cheer.generalmodule.util.StringUtils;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.leaugebar.R;
import com.sicnu.cheer.leaugebar.adapter.HomeLeftMenuAdapter;
import com.sicnu.cheer.leaugebar.app.App;
import com.sicnu.cheer.leaugebar.bean.MenuBean;
import com.sicnu.cheer.generalmodule.bean.MyUser;
import com.sicnu.cheer.leaugebar.bean.Update;
import com.sicnu.cheer.leaugebar.fragment.ContactsParentFragment;
import com.sicnu.cheer.leaugebar.fragment.EventParentFragment;
import com.sicnu.cheer.leaugebar.fragment.ManageParentFragment;
import com.sicnu.cheer.leaugebar.fragment.MessageParentFragment;
import com.sicnu.cheer.leaugebar.leaguemodle.activity.LeagueMainActivity;
import com.sicnu.cheer.leaugebar.utils.UpdateManager;
import com.sicnu.cheer.leaugebar.wigets.SharePopupWindow;
import com.sicnu.cheer.profileset.activity.AboutUsActivity;
import com.sicnu.cheer.profileset.activity.FeedbackActivity;
import com.sicnu.cheer.profileset.activity.MyProfileActivity;
import com.sicnu.cheer.profileset.config.Constant;
import com.srx.widget.TabBarView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.InjectView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.update.BmobUpdateAgent;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

/**
 * Created by cheer on 2017/1/2.
 * 主页面框架和右划菜单页
 */
public class MainActivity extends BaseActivity {
    private List<MenuBean> list;
    private HomeLeftMenuAdapter adapter;
    private EventParentFragment eventParentFragment;
    private ContactsParentFragment contactsFragment;
    private MessageParentFragment messFragment;
    private ManageParentFragment manageParentFragment;

    @InjectView(R.id.tabBarView)
    TabBarView tabBarView;//可折叠的底部导航按钮

    private ListView listView;
    private SlidingMenu slidingMenu;
    private FragmentManager fragmentManager;
    private View slideView;
    private ProgressDialog progressDialog;

    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        super.initView();
        fillListData();
        slideView = LayoutInflater.from(this).inflate(R.layout.home_menu, null);

        //退出登录操作
        slideView.findViewById(R.id.logout_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UIHelper.showDialog(mThis, "提示", "确定退出吗？", new UIHelper.DialogCallback() {
                    @Override
                    public void confirmCallBack() {
                        BmobUser.logOut(mThis);
                        Intent intent = new Intent(mThis, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void cancelCallBack() {

                    }
                });
            }
        });
        //侧滑菜单设置
        setSlidingMenu();

        //设置底部导航按钮
        setupTabView();

        //检查更新
        checkVersion();
    }

    @Override
    protected void initData() {
        super.initData();
        fragmentManager = getSupportFragmentManager();
        setTabSelection(0);

        progressDialog = new ProgressDialog(mThis);
        progressDialog.setMessage("加载中...");
        saveDownloadUrl();
        getToken();
    }

    private void saveDownloadUrl() {
        BmobQuery<Update> query=new BmobQuery<>();
        query.findObjects(mThis, new FindListener<Update>() {
            @Override
            public void onSuccess(List<Update> list) {
                SharedPreferencesUtil.saveUserItem(mThis,"downloadUrl",list.get(0).getDownloadUrl());
            }
            @Override
            public void onError(int i, String s) {
                Log.d("get download url error", "onError: "+s);
            }
        });
    }

    private void getToken() {
        if (!NetWorkUtil.isConnect(mThis)){
            UIHelper.ToastMessage(mThis,"没有网络，请设置！");
            return;
        }
        String token = MyUser.getCurrentUser(mThis,MyUser.class).getToken();
        if (StringUtils.isEmpty(token)) {
            String url = "http://api.cn.ronghub.com/user/getToken.json";
            MyUser myUser = MyUser.getCurrentUser(mThis, MyUser.class);
            Map params = new HashMap();
            params.put("userId", myUser.getObjectId());
            params.put("name", myUser.getNick());
            if (myUser.getHeadPic()==null) {
                myUser.setHeadPic("");
            }
            params.put("portraitUri", Uri.parse(myUser.getHeadPic()));
            HttpAccessUtils.callHttpAccess(url, params, new HttpAccessUtils.HttpAccessCallBack() {
                @Override
                public void callback(String result) {
                    if (result != null) {
                        try {
                            JSONObject resultJson = new JSONObject(result);
                            int code = resultJson.optInt("code", 0);
                            if (code == 200) {
                                final String token = resultJson.optString("token");
                                MyUser newUser = MyUser.getCurrentUser(mThis, MyUser.class);
                                newUser.setToken(token);
                                newUser.update(mThis, newUser.getObjectId(), new UpdateListener() {
                                    @Override
                                    public void onSuccess() {
                                        connect(token);
                                    }
                                    @Override
                                    public void onFailure(int i, String s) {
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            progressDialog.dismiss();
                            e.printStackTrace();
                        }
                    }
                }
            });
        } else {
            connect(token);
        }

    }

    private void connect(String token) {
        progressDialog.show();
        if (getApplicationInfo().packageName.equals(App.getCurProcessName(getApplicationContext()))) {
            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                /**
                 * Token 错误。可以从下面两点检查
                 * 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
                 * 2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
                 */
                @Override
                public void onTokenIncorrect() {
                    UIHelper.ToastMessage(mThis, "token失效");
                    progressDialog.dismiss();
//                    getToken();
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token 对应的用户 id
                 */
                @Override
                public void onSuccess(String userid) {
                    progressDialog.dismiss();
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    progressDialog.dismiss();
                }
            });
        }
    }


    //填充菜单ListView中的list
    private void fillListData() {
        list = new ArrayList<>();
        int imageIds[] = {-1, R.mipmap.share_set, R.mipmap.my_league, R.mipmap.my_profile,
                -1, R.mipmap.suggesstion, R.mipmap.version_set, R.mipmap.about_set,};
        String content[] = {"分享与设置", "推荐", "我的社团", "个人资料",
                "联系与反馈", "意见建议", "检查更新", "关于我们"};
        for (int i = 0; i < content.length; i++) {
            MenuBean drawerBean = new MenuBean();
            drawerBean.setImgId(imageIds[i]);
            drawerBean.setText(content[i]);
            list.add(drawerBean);
        }
    }

    /**
     * 切换Fragment操作
     *
     * @param tabSelection
     */
    public void setTabSelection(int tabSelection) {

        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragments(transaction);
        switch (tabSelection) {
            case 0:
                if (eventParentFragment == null) {
                    eventParentFragment = new EventParentFragment();
                    transaction.add(R.id.home_fl, eventParentFragment);
                } else {
                    transaction.show(eventParentFragment);
                }
                break;

            case 1:
                if (messFragment == null) {
                    messFragment = new MessageParentFragment();
                    transaction.add(R.id.home_fl, messFragment);
                } else {
                    transaction.show(messFragment);
                }
                break;
            case 3:
                if (manageParentFragment == null) {
                    manageParentFragment = new ManageParentFragment();
                    transaction.add(R.id.home_fl, manageParentFragment);
                } else {
                    transaction.show(manageParentFragment);
                }
                break;
            case 4:
                if (contactsFragment == null) {
                    contactsFragment = new ContactsParentFragment();
                    transaction.add(R.id.home_fl, contactsFragment);
                } else {
                    transaction.show(contactsFragment);
                }
                break;
            default:
                break;
        }
        transaction.commit();
    }

    /**
     * 隐藏所有的fragments
     *
     * @param transaction
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (eventParentFragment != null) {
            transaction.hide(eventParentFragment);
        }
        if (contactsFragment != null) {
            transaction.hide(contactsFragment);
        }
        if (messFragment != null) {
            transaction.hide(messFragment);
        }
        if (manageParentFragment != null) {
            transaction.hide(manageParentFragment);
        }
    }


    /**
     * 设置slidingmenu的一些属性
     */
    public void setSlidingMenu() {
        //获取登录用户，填充头像和昵称
        MyUser currentUser = MyUser.getCurrentUser(mThis, MyUser.class);

        ImageView userHead = (ImageView) slideView.findViewById(R.id.user_head_iv);
        Glide.with(mThis).load(currentUser.getHeadPic()).placeholder(R.mipmap.default_user_img).into(userHead);
        TextView userName = (TextView) slideView.findViewById(R.id.user_name_tv);
        userName.setText(currentUser.getNick());

        listView = (ListView) slideView.findViewById(R.id.menu_lv);
        adapter = new HomeLeftMenuAdapter(list);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                MenuAction(i);
            }
        });

        int width = ScreenUtils.getScreenWidth(mThis);
        slidingMenu = new SlidingMenu(this);
        slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        slidingMenu.setMenu(slideView);
        slidingMenu.setMode(SlidingMenu.LEFT);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        slidingMenu.setBehindOffset(width / 4);
    }

    private void MenuAction(int i) {
        Intent intent = new Intent();
        switch (i) {
            case 1:
                PopupWindow popupWindow = new SharePopupWindow(mThis);
                popupWindow.showAtLocation(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0), Gravity.BOTTOM, 0, 0);
                break;
            case 2:
                if (MyUser.getCurrentUser(mThis, MyUser.class).getLeague() != null) {
                    intent.setClass(mThis, LeagueMainActivity.class);
                    startActivity(intent);
                } else {
                    UIHelper.ToastMessage(mThis, "您当前没有社团");
                }
                break;
            case 3:
                intent.setClass(mThis, MyProfileActivity.class);
                startActivityForResult(intent, 0);
                break;
            case 5:
                intent.setClass(mThis, FeedbackActivity.class);
                startActivity(intent);
                break;
            case 6:
                UpdateManager.getUpdateManager().checkAppUpdate(this, true, true);
                break;
            case 7:
                intent.setClass(mThis, AboutUsActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void setupTabView() {
        //设置主按钮图标
        tabBarView.setMainBitmap(R.mipmap.icon_menu);

        //设置菜单对应位置按钮图标及两侧图标
        tabBarView.bindBtnsForPage(0, R.mipmap.icon_event, 0, 0);//活动
        tabBarView.bindBtnsForPage(1, R.mipmap.icon_message, 0, 0);//消息
        tabBarView.bindBtnsForPage(2, R.mipmap.icon_manage, 0, 0);//设置
        tabBarView.bindBtnsForPage(3, R.mipmap.icon_contacts, 0, 0);//联系人

        //设置初始默认选中
        tabBarView.initializePage(0);

        //添加监听
        tabBarView.setOnTabBarClickListener(onTabBarClickListener);
    }

    //监听回调
    private TabBarView.OnTabBarClickListener onTabBarClickListener = new TabBarView.OnTabBarClickListener() {

        @Override
        public void onMainBtnsClick(int position, int[] clickLocation) {
            //点击菜单
            setTabSelection(position);
        }

        @Override
        public void onMainBtnsClick(int position) {
            //点击菜单
            setTabSelection(position);
        }

        @Override
        public void onLeftBtnClick(int page) {
            //点击对应菜单的左侧按钮
        }

        @Override
        public void onRightBtnClick(int page) {
            //点击对应菜单的右侧按钮
        }
    };

    @Override
    public void onBackPressed() {
        if (slidingMenu.isMenuShowing()) {
            slidingMenu.toggle();
        } else {
            exitBy2Click();
        }
    }

    /**
     * 双击退出函数
     *  
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            finish();
            AppManager.getAppManager().AppExit(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constant.RESULT_FROM_PROFILE_SET) {
            //获取登录用户，填充头像和昵称
            MyUser currentUser = MyUser.getCurrentUser(mThis, MyUser.class);
            ImageView userHead = (ImageView) slideView.findViewById(R.id.user_head_iv);
            Glide.with(mThis).load(currentUser.getHeadPic()).placeholder(R.mipmap.default_user_img).into(userHead);
            TextView userName = (TextView) slideView.findViewById(R.id.user_name_tv);
            userName.setText(currentUser.getNick());
            if (data!=null) {
                if (data.getBooleanExtra("changeLeague", false)&&manageParentFragment!=null) {
                    if (manageParentFragment.childFragment!=null) {
                        manageParentFragment.childFragment.checkManager();
                    }
                }
            }
        }
    }

    private boolean isClickHome;
    /**
     * 接收器来监听home键的监听，因为程序更新需要（如果退回桌面，重新进入程序需要检查更新）
     */
    private final BroadcastReceiver homeReceiver = new BroadcastReceiver() {
        final String SYS_KEY = "reason"; //标注下这里必须是这么一个字符串值
        final String SYS_HOME_KEY = "homekey";//标注下这里必须是这么一个字符串值

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYS_KEY);
                if (reason != null && reason.equals(SYS_HOME_KEY)) {
                    Log.i("TT", "##################home键监听");
                    SharedPreferencesUtil.saveTimeByKey(mThis,"homekeyClick");
                    isClickHome = true;
                }
            }
        }
    };

    private void checkVersion() {
        IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(homeReceiver, homeFilter);
        //检查新版本
        if (isClickHome) {
            UpdateManager.getUpdateManager().checkAppUpdate(this, false, true);
            isClickHome = false;
        } else {
            UpdateManager.getUpdateManager().checkAppUpdate(this, false, true);
        }
    }
}
